import React, {PureComponent} from "react";
import {connect} from "react-redux";
import {Button, Icon, Input, Modal, notification, Radio, Table, Upload} from "antd";
import {createNew, importConsolidate, query} from "./actions";
import {tableProps} from "../../lib/ui";
import lodash from 'lodash';
import {getCurrentOrganization, getPrincipal} from "../../lib/identity";
import {lock, unlock} from "../hisZadOrderReceivable/actions";

const {TextArea} = Input;

class Toolbar extends PureComponent {
    // dataList 为导入失败的列表
    state = {visible: false, historyZadOrderImportDtos: []};
    customRequest = (options) => {
        const {dispatch, filter = {}} = this.props;
        dispatch(importConsolidate({
            file: options.file
        })).then(action => {
            if (action.payload && action.payload.importDtos.length === 0) {
                notification.success({
                    message: '导入成功'
                });
            } else {
                const dataList = action.payload.importDtos;
                const size = dataList.length;
                for (let i = 0; i < size; i++) {
                    const item = dataList[i];
                    item.id = Math.random().toString();
                    item.selectType = undefined;
                }
                this.setState({
                    visible: true, historyZadOrderImportDtos: [...dataList]
                });
            }
            dispatch(query({...filter, "organizationId": getCurrentOrganization(), "type": "OUT"}));
        });
    };
    uploadProps = {
        showUploadList: false, name: 'file', accept: '.xls, .xlsx, .csv', customRequest: this.customRequest
    };

    handleCreateNew = () => {
        const historyZadOrderImportDtos = this.state.historyZadOrderImportDtos;
        if (historyZadOrderImportDtos.length === 0) {
            notification.error({
                message: '没有新增的订单数据'
            });
            return;
        }
        const {dispatch, filter = {}} = this.props;
        const newList = [];
        const size = historyZadOrderImportDtos.length;
        for (let i = 0; i < size; i++) {
            const item = historyZadOrderImportDtos[i];
            if (item.selectType === 2) {
                newList.push(item);
            }
        }
        if (newList.length > 0) {
            dispatch(createNew(newList)).then(() => {
                notification.success({
                    message: '导入成功'
                });
                dispatch(query({...filter, "organizationId": getCurrentOrganization(), "type": "OUT"}));
            });
        }
        this.setState({visible: false, historyZadOrderImportDtos: []});
    };

    handleCancelModal = () => {
        this.setState({visible: false, historyZadOrderImportDtos: []});
    };

    handleExport = () => {
        const {selectedRowKeys} = this.props;
        document.getElementById("ids").value = lodash.join(selectedRowKeys, ",");
        document.getElementById("export").submit();
        notification.success({
            message: '请等待文件导出'
        });
    }

    handleLock = () => {
        const {dispatch, selectedRowKeys, filter} = this.props;
        dispatch(lock({"ids": selectedRowKeys})).then(() => {
            dispatch(query({...filter, "organizationId": getCurrentOrganization(), "type": "OUT"}));
        });
    };

    handleUnlock = () => {
        const {dispatch, selectedRowKeys, filter} = this.props;
        dispatch(unlock({"ids": selectedRowKeys})).then(() => {
            dispatch(query({...filter, "organizationId": getCurrentOrganization(), "type": "OUT"}));
        });
    };

    onChange = (value, record) => {
        const historyZadOrderImportDtos = this.state.historyZadOrderImportDtos;
        const found = historyZadOrderImportDtos.find(item => item.id === record.id);
        found.selectType = value;
        this.setState({
            historyZadOrderImportDtos: [...historyZadOrderImportDtos]
        });
    };

    render() {
        const {importLoading} = this.props;
        const columns = [{
            title: "错误消息", dataIndex: "importErrorMessage", width: '600px', ellipsis: true
        }, {
            title: "操作", dataIndex: "", width: '300px', render: (text, record) => {
                return <Radio.Group onChange={e => this.onChange(e.target.value, record)} value={record.selectType}>
                    <Radio value={1}>有误，取消导入</Radio>
                    <Radio value={2}>确认新增订单</Radio>
                </Radio.Group>
            }
        }];
        return (<div className="actions">
                <Button href="/static/班列应付历史数据导入模板.xlsx" target="_blank">下载导入模板</Button>
                <Upload {...this.uploadProps}>
                    <Button disabled={importLoading}>
                        <Icon type="upload"/> 导入
                    </Button>
                </Upload>
                <Button disabled={this.props.selectedRowKeys.length === 0} onClick={this.handleExport}><Icon
                    type="export"/>勾选导出</Button>
                {getPrincipal().admin &&
                    <Button disabled={this.props.selectedRowKeys.length === 0} onClick={this.handleLock}><Icon
                        type="export"/>锁定</Button>}
                {getPrincipal().admin &&
                    <Button disabled={this.props.selectedRowKeys.length === 0} onClick={this.handleUnlock}><Icon
                        type="export"/>解锁</Button>}
                <Modal
                    visible={this.state.visible}
                    title="柜号重复，请选择操作"
                    onCancel={this.handleCancelModal}
                    cancelText={"取消"}
                    okText={"确认"}
                    onOk={this.handleCreateNew}
                    maskClosable={false}
                    width={"50%"}
                >
                    <Table
                        {...tableProps}
                        bordered
                        columns={columns}
                        dataSource={this.state.historyZadOrderImportDtos}
                    />
                </Modal>
                <form
                    id="export"
                    method="post"
                    target="_blank"
                    action="/api/hisZadOrder/export"
                >
                    <input
                        name="type"
                        type="hidden"
                        value="OUT"
                    />
                    <input
                        id="ids"
                        name="ids"
                        type="hidden"
                    />
                </form>
            </div>

        );
    }
}

const mapStateToProps = state => {
    return {
        ...state.hisZadOrderPayable.list
    };
};

export default connect(mapStateToProps)(Toolbar);
